function __parseGraphdata(realtime_values, stocks){
  var labels = [];
  var data = [];
  var sum = 0;
  for (var x = 0; x < stocks.length; x++) {
    var stock = stocks[x];
    var newDate = new Date(stock["buydate"]).toLocaleDateString('de-DE');
    labels.push(newDate);
    sum += Math.round(parseFloat(stock["boughtfor"]));
    data.push(sum);
  }
  __createGraph(labels, data);
}

async function getGraph(realtime_values){
  const stocksUrl = "getCurrentStocks";
  fetch(stocksUrl)
  .then(response => {
    if (response.ok) return response.json();
    else throw new Error("request failed");
  })
  .then(stocks => {
    __parseGraphdata(realtime_values, stocks);
  })
  .catch(error => {
    // if it fails wait 0.2s and repeat
    console.log("Creating Graph failed. Retrying in 0.2s..");
    console.log("Error:");
    console.log(e);
    setTimeout(function() {
      getGraph(realtime_values);
    }, 200);
  });
}

function __createGraph(gLabels, gData) {
  var ctx = document.getElementById('mainStockValueChart');
  var myChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: gLabels,
        datasets: [{
          data: gData,
          label: 'Summe der Aktienwerte'
        }]
      },
      options: {
          maintainAspectRatio: false,
          responsive: true,
      }
  });
}
